<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
	<title>SQLAlchemy 0.4 Documentation - module sqlalchemy.ext.sqlsoup</title>
	
    
    <link rel="stylesheet" href="style.css"></link>
    <link rel="stylesheet" href="docs.css"></link>
    <link href="syntaxhighlight.css" rel="stylesheet" type="text/css"></link>
    <script src="scripts.js"></script>

    <link rel="stylesheet" href="docutil.css"></link>



</head>
<body>








<div id="topanchor"><a name="top">&nbsp;</a></div>


<h1>SQLAlchemy 0.4 Documentation</h1>

<div id="pagecontrol"><a href="index.html">Multiple Pages</a> | <a href="documentation.html">One Page</a></div>

<div class="versionheader">Version: 0.4.8   Last Updated: 10/12/08 13:33:19</div>












    <div class="topnav">

    
    <div class="navbanner">
        <a href="index.html" class="totoc">Table of Contents</a>
        
    <div class="prevnext">
            Up: <a href="docstrings.html">API Documentation</a>

               |   
            Previous: <a href="sqlalchemy_ext_orderinglist.html">module sqlalchemy.ext.orderinglist</a>

               |   
            Next: <a href="sqlalchemy_databases_sqlite.html">module sqlalchemy.databases.sqlite</a>
    </div>

        <h2>module sqlalchemy.ext.sqlsoup</h2>
    </div>

	
	
    <ul>
        
        <li><a style="" href="sqlalchemy_ext_sqlsoup.html#docstrings_sqlalchemy.ext.sqlsoup_PKNotFoundError">class PKNotFoundError(SQLAlchemyError)</a></li>

        
        <li><a style="" href="sqlalchemy_ext_sqlsoup.html#docstrings_sqlalchemy.ext.sqlsoup_SqlSoup">class SqlSoup()</a></li>

    </ul>

	</div>



    

    
    
    <A name="docstrings_sqlalchemy.ext.sqlsoup"></a>
    
    <div class="sectionL2">

    <h3>module sqlalchemy.ext.sqlsoup</h3>
    
    
    <div class="darkcell"><div class="section">
<h1><a id="introduction" name="introduction">Introduction</a></h1>
<p>SqlSoup provides a convenient way to access database tables without
having to declare table or mapper classes ahead of time.</p>
<p>Suppose we have a database with users, books, and loans tables
(corresponding to the PyWebOff dataset, if you're curious).  For
testing purposes, we'll create this db as follows:</p>
<pre class="literal-block">
&gt;&gt;&gt; from sqlalchemy import create_engine
&gt;&gt;&gt; e = create_engine('sqlite:///:memory:')
&gt;&gt;&gt; for sql in _testsql: e.execute(sql) #doctest: +ELLIPSIS
&lt;...
</pre>
<p>Creating a SqlSoup gateway is just like creating an SQLAlchemy
engine:</p>
<pre class="literal-block">
&gt;&gt;&gt; from sqlalchemy.ext.sqlsoup import SqlSoup
&gt;&gt;&gt; db = SqlSoup('sqlite:///:memory:')
</pre>
<p>or, you can re-use an existing metadata or engine:</p>
<pre class="literal-block">
&gt;&gt;&gt; db = SqlSoup(MetaData(e))
</pre>
<p>You can optionally specify a schema within the database for your
SqlSoup:</p>
<pre class="literal-block">
# &gt;&gt;&gt; db.schema = myschemaname
</pre>
</div>
<div class="section">
<h1><a id="loading-objects" name="loading-objects">Loading objects</a></h1>
<p>Loading objects is as easy as this:</p>
<pre class="literal-block">
&gt;&gt;&gt; users = db.users.all()
&gt;&gt;&gt; users.sort()
&gt;&gt;&gt; users
<b>64;example.edu',password='student',classname=None,admin=0), MappedUsers(name='Bhargan Basepair',email='basepair&#64;example.edu',password='basepair',classname=None,admin=1)</b>
</pre>
<p>Of course, letting the database do the sort is better:</p>
<pre class="literal-block">
&gt;&gt;&gt; db.users.order_by(db.users.name).all()
<b>64;example.edu',password='basepair',classname=None,admin=1), MappedUsers(name='Joe Student',email='student&#64;example.edu',password='student',classname=None,admin=0)</b>
</pre>
<p>Field access is intuitive:</p>
<pre class="literal-block">
&gt;&gt;&gt; users[0].email
u'student&#64;example.edu'
</pre>
<p>Of course, you don't want to load all users very often.  Let's add a
WHERE clause.  Let's also switch the order_by to DESC while we're at
it:</p>
<pre class="literal-block">
&gt;&gt;&gt; from sqlalchemy import or_, and_, desc
&gt;&gt;&gt; where = or_(db.users.name=='Bhargan Basepair', db.users.email=='student&#64;example.edu')
&gt;&gt;&gt; db.users.filter(where).order_by(desc(db.users.name)).all()
<b>64;example.edu',password='student',classname=None,admin=0), MappedUsers(name='Bhargan Basepair',email='basepair&#64;example.edu',password='basepair',classname=None,admin=1)</b>
</pre>
<p>You can also use .first() (to retrieve only the first object from a query) or
.one() (like .first when you expect exactly one user -- it will raise an
exception if more were returned):</p>
<pre class="literal-block">
&gt;&gt;&gt; db.users.filter(db.users.name=='Bhargan Basepair').one()
MappedUsers(name='Bhargan Basepair',email='basepair&#64;example.edu',password='basepair',classname=None,admin=1)
</pre>
<p>Since name is the primary key, this is equivalent to</p>
<blockquote>
<pre class="doctest-block">
&gt;&gt;&gt; db.users.get('Bhargan Basepair')
MappedUsers(name='Bhargan Basepair',email='basepair&#64;example.edu',password='basepair',classname=None,admin=1)
</pre>
</blockquote>
<p>This is also equivalent to</p>
<blockquote>
<pre class="doctest-block">
&gt;&gt;&gt; db.users.filter_by(name='Bhargan Basepair').one()
MappedUsers(name='Bhargan Basepair',email='basepair&#64;example.edu',password='basepair',classname=None,admin=1)
</pre>
</blockquote>
<p>filter_by is like filter, but takes kwargs instead of full clause expressions.
This makes it more concise for simple queries like this, but you can't do
complex queries like the or_ above or non-equality based comparisons this way.</p>
<div class="section">
<h2><a id="full-query-documentation" name="full-query-documentation">Full query documentation</a></h2>
<p>Get, filter, filter_by, order_by, limit, and the rest of the
query methods are explained in detail in the <a class="reference" href="http://www.sqlalchemy.org/docs/04/ormtutorial.html#datamapping_querying">SQLAlchemy documentation</a>.</p>
</div>
</div>
<div class="section">
<h1><a id="modifying-objects" name="modifying-objects">Modifying objects</a></h1>
<p>Modifying objects is intuitive:</p>
<pre class="literal-block">
&gt;&gt;&gt; user = _
&gt;&gt;&gt; user.email = 'basepair+nospam&#64;example.edu'
&gt;&gt;&gt; db.flush()
</pre>
<p>(SqlSoup leverages the sophisticated SQLAlchemy unit-of-work code, so
multiple updates to a single object will be turned into a single
<tt class="docutils literal"><span class="pre">UPDATE</span></tt> statement when you flush.)</p>
<p>To finish covering the basics, let's insert a new loan, then delete
it:</p>
<pre class="literal-block">
&gt;&gt;&gt; book_id = db.books.filter_by(title='Regional Variation in Moss').first().id
&gt;&gt;&gt; db.loans.insert(book_id=book_id, user_name=user.name)
MappedLoans(book_id=2,user_name='Bhargan Basepair',loan_date=None)
&gt;&gt;&gt; db.flush()

&gt;&gt;&gt; loan = db.loans.filter_by(book_id=2, user_name='Bhargan Basepair').one()
&gt;&gt;&gt; db.delete(loan)
&gt;&gt;&gt; db.flush()
</pre>
<p>You can also delete rows that have not been loaded as objects. Let's
do our insert/delete cycle once more, this time using the loans
table's delete method. (For SQLAlchemy experts: note that no flush()
call is required since this delete acts at the SQL level, not at the
Mapper level.) The same where-clause construction rules apply here as
to the select methods.</p>
<pre class="literal-block">
&gt;&gt;&gt; db.loans.insert(book_id=book_id, user_name=user.name)
MappedLoans(book_id=2,user_name='Bhargan Basepair',loan_date=None)
&gt;&gt;&gt; db.flush()
&gt;&gt;&gt; db.loans.delete(db.loans.book_id==2)
</pre>
<p>You can similarly update multiple rows at once. This will change the
book_id to 1 in all loans whose book_id is 2:</p>
<pre class="literal-block">
&gt;&gt;&gt; db.loans.update(db.loans.book_id==2, book_id=1)
&gt;&gt;&gt; db.loans.filter_by(book_id=1).all()
[MappedLoans(book_id=1,user_name='Joe Student',loan_date=datetime.datetime(2006, 7, 12, 0, 0))]
</pre>
</div>
<div class="section">
<h1><a id="joins" name="joins">Joins</a></h1>
<p>Occasionally, you will want to pull out a lot of data from related
tables all at once.  In this situation, it is far more efficient to
have the database perform the necessary join.  (Here we do not have <em>a
lot of data</em> but hopefully the concept is still clear.)  SQLAlchemy is
smart enough to recognize that loans has a foreign key to users, and
uses that as the join condition automatically.</p>
<pre class="literal-block">
&gt;&gt;&gt; join1 = db.join(db.users, db.loans, isouter=True)
&gt;&gt;&gt; join1.filter_by(name='Joe Student').all()
<b>64;example.edu',password='student',classname=None,admin=0,book_id=1,user_name='Joe Student',loan_date=datetime.datetime(2006, 7, 12, 0, 0))</b>
</pre>
<p>If you're unfortunate enough to be using MySQL with the default MyISAM
storage engine, you'll have to specify the join condition manually,
since MyISAM does not store foreign keys.  Here's the same join again,
with the join condition explicitly specified:</p>
<pre class="literal-block">
&gt;&gt;&gt; db.join(db.users, db.loans, db.users.name==db.loans.user_name, isouter=True)
&lt;class 'sqlalchemy.ext.sqlsoup.MappedJoin'&gt;
</pre>
<p>You can compose arbitrarily complex joins by combining Join objects
with tables or other joins.  Here we combine our first join with the
books table:</p>
<pre class="literal-block">
&gt;&gt;&gt; join2 = db.join(join1, db.books)
&gt;&gt;&gt; join2.all()
<b>64;example.edu',password='student',classname=None,admin=0,book_id=1,user_name='Joe Student',loan_date=datetime.datetime(2006, 7, 12, 0, 0),id=1,title='Mustards I Have Known',published_year='1989',authors='Jones')</b>
</pre>
<p>If you join tables that have an identical column name, wrap your join
with <cite>with_labels</cite>, to disambiguate columns with their table name
(.c is short for .columns):</p>
<pre class="literal-block">
&gt;&gt;&gt; db.with_labels(join1).c.keys()
[u'users_name', u'users_email', u'users_password', u'users_classname', u'users_admin', u'loans_book_id', u'loans_user_name', u'loans_loan_date']
</pre>
<p>You can also join directly to a labeled object:</p>
<pre class="literal-block">
&gt;&gt;&gt; labeled_loans = db.with_labels(db.loans)
&gt;&gt;&gt; db.join(db.users, labeled_loans, isouter=True).c.keys()
[u'name', u'email', u'password', u'classname', u'admin', u'loans_book_id', u'loans_user_name', u'loans_loan_date']
</pre>
</div>
<div class="section">
<h1><a id="relations" name="relations">Relations</a></h1>
<p>You can define relations on SqlSoup classes:</p>
<blockquote>
<pre class="doctest-block">
&gt;&gt;&gt; db.users.relate('loans', db.loans)
</pre>
</blockquote>
<p>These can then be used like a normal SA property:</p>
<blockquote>
<pre class="doctest-block">
&gt;&gt;&gt; db.users.get('Joe Student').loans
[MappedLoans(book_id=1,user_name='Joe Student',loan_date=datetime.datetime(2006, 7, 12, 0, 0))]
</pre>
<pre class="doctest-block">
&gt;&gt;&gt; db.users.filter(~db.users.loans.any()).all()
<b>64;example.edu',password='basepair',classname=None,admin=1)</b>
</pre>
</blockquote>
<p>relate can take any options that the relation function accepts in normal mapper definition:</p>
<blockquote>
<pre class="doctest-block">
&gt;&gt;&gt; del db._cache['users']
&gt;&gt;&gt; db.users.relate('loans', db.loans, order_by=db.loans.loan_date, cascade='all, delete-orphan')
</pre>
</blockquote>
</div>
<div class="section">
<h1><a id="advanced-use" name="advanced-use">Advanced Use</a></h1>
<div class="section">
<h2><a id="accessing-the-session" name="accessing-the-session">Accessing the Session</a></h2>
<p>SqlSoup uses a SessionContext to provide thread-local sessions.  You
can get a reference to the current one like this:</p>
<pre class="literal-block">
&gt;&gt;&gt; from sqlalchemy.ext.sqlsoup import objectstore
&gt;&gt;&gt; session = objectstore.current
</pre>
<p>Now you have access to all the standard session-based SA features,
such as transactions.  (SqlSoup's <tt class="docutils literal"><span class="pre">flush()</span></tt> is normally
transactionalized, but you can perform manual transaction management
if you need a transaction to span multiple flushes.)</p>
</div>
<div class="section">
<h2><a id="mapping-arbitrary-selectables" name="mapping-arbitrary-selectables">Mapping arbitrary Selectables</a></h2>
<p>SqlSoup can map any SQLAlchemy <tt class="docutils literal"><span class="pre">Selectable</span></tt> with the map
method. Let's map a <tt class="docutils literal"><span class="pre">Select</span></tt> object that uses an aggregate function;
we'll use the SQLAlchemy <tt class="docutils literal"><span class="pre">Table</span></tt> that SqlSoup introspected as the
basis. (Since we're not mapping to a simple table or join, we need to
tell SQLAlchemy how to find the <em>primary key</em> which just needs to be
unique within the select, and not necessarily correspond to a <em>real</em>
PK in the database.)</p>
<pre class="literal-block">
&gt;&gt;&gt; from sqlalchemy import select, func
&gt;&gt;&gt; b = db.books._table
&gt;&gt;&gt; s = select([b.c.published_year, func.count('*').label('n')], from_obj=[b], group_by=[b.c.published_year])
&gt;&gt;&gt; s = s.alias('years_with_count')
&gt;&gt;&gt; years_with_count = db.map(s, primary_key=[s.c.published_year])
&gt;&gt;&gt; years_with_count.filter_by(published_year='1989').all()
[MappedBooks(published_year='1989',n=1)]
</pre>
<p>Obviously if we just wanted to get a list of counts associated with
book years once, raw SQL is going to be less work. The advantage of
mapping a Select is reusability, both standalone and in Joins. (And if
you go to full SQLAlchemy, you can perform mappings like this directly
to your object models.)</p>
<p>An easy way to save mapped selectables like this is to just hang them on
your db object:</p>
<pre class="literal-block">
&gt;&gt;&gt; db.years_with_count = years_with_count
</pre>
<p>Python is flexible like that!</p>
</div>
<div class="section">
<h2><a id="raw-sql" name="raw-sql">Raw SQL</a></h2>
<p>SqlSoup works fine with SQLAlchemy's <a class="reference" href="http://www.sqlalchemy.org/docs/04/sqlexpression.html#sql_text">text block support</a>.</p>
<p>You can also access the SqlSoup's <cite>engine</cite> attribute to compose SQL
directly.  The engine's <tt class="docutils literal"><span class="pre">execute</span></tt> method corresponds to the one of a
DBAPI cursor, and returns a <tt class="docutils literal"><span class="pre">ResultProxy</span></tt> that has <tt class="docutils literal"><span class="pre">fetch</span></tt> methods
you would also see on a cursor:</p>
<pre class="literal-block">
&gt;&gt;&gt; rp = db.bind.execute('select name, email from users order by name')
&gt;&gt;&gt; for name, email in rp.fetchall(): print name, email
Bhargan Basepair basepair+nospam&#64;example.edu
Joe Student student&#64;example.edu
</pre>
<p>You can also pass this engine object to other SQLAlchemy constructs.</p>
</div>
<div class="section">
<h2><a id="dynamic-table-names" name="dynamic-table-names">Dynamic table names</a></h2>
<p>You can load a table whose name is specified at runtime with the entity() method:</p>
<blockquote>
<pre class="doctest-block">
&gt;&gt;&gt; tablename = 'loans'
&gt;&gt;&gt; db.entity(tablename) == db.loans
True
</pre>
</blockquote>
</div>
</div>
<div class="section">
<h1><a id="extra-tests" name="extra-tests">Extra tests</a></h1>
<p>Boring tests here.  Nothing of real expository value.</p>
<pre class="literal-block">
&gt;&gt;&gt; db.users.filter_by(classname=None).order_by(db.users.name).all()
<b>64;example.edu',password='basepair',classname=None,admin=1), MappedUsers(name='Joe Student',email='student&#64;example.edu',password='student',classname=None,admin=0)</b>

&gt;&gt;&gt; db.nopk
Traceback (most recent call last):
...
PKNotFoundError: table 'nopk' does not have a primary key defined [columns: i]

&gt;&gt;&gt; db.nosuchtable
Traceback (most recent call last):
...
NoSuchTableError: nosuchtable

&gt;&gt;&gt; years_with_count.insert(published_year='2007', n=1)
Traceback (most recent call last):
...
InvalidRequestError: SQLSoup can only modify mapped Tables (found: Alias)

[tests clear()]
&gt;&gt;&gt; db.loans.count()
1
&gt;&gt;&gt; _ = db.loans.insert(book_id=1, user_name='Bhargan Basepair')
&gt;&gt;&gt; db.clear()
&gt;&gt;&gt; db.flush()
&gt;&gt;&gt; db.loans.count()
1
</pre>
</div>
</div>
    


            
    

    
    
    <A name="docstrings_sqlalchemy.ext.sqlsoup_PKNotFoundError"></a>
    
    <div class="sectionL3">

    <h3>class PKNotFoundError(<a href="sqlalchemy_exceptions.html#docstrings_sqlalchemy.exceptions_SQLAlchemyError">SQLAlchemyError</a>)</h3>
    
    
    


    

            <a href="#top" class="totoc">back to section top</a>
    </div>



            
    

    
    
    <A name="docstrings_sqlalchemy.ext.sqlsoup_SqlSoup"></a>
    
    <div class="sectionL3">

    <h3>class SqlSoup()</h3>
    
    
    

                    
    <div class="darkcell">
    
    <A name=""></a>
    <b>def __init__(<i>self</i>, <i>*args</i>, <i>**kwargs</i>)</b>
    <div class="docstring">
    <p>Initialize a new <tt class="docutils literal"><span class="pre">SqlSoup</span></tt>.</p>
<p><cite>args</cite> may either be an <tt class="docutils literal"><span class="pre">SQLEngine</span></tt> or a set of arguments
suitable for passing to <tt class="docutils literal"><span class="pre">create_engine</span></tt>.</p>

    </div>
    </div>

                    
         <div class="darkcell">
         <A name=""></a>
         <b>bind = property()</b>
         <div class="docstring">
         
         </div> 
         </div>

                    
    <div class="darkcell">
    
    <A name=""></a>
    <b>def clear(<i>self</i>)</b>
    <div class="docstring">
    
    </div>
    </div>

                    
    <div class="darkcell">
    
    <A name=""></a>
    <b>def delete(<i>self</i>, <i>*args</i>, <i>**kwargs</i>)</b>
    <div class="docstring">
    
    </div>
    </div>

                    
         <div class="darkcell">
         <A name=""></a>
         <b>engine = property()</b>
         <div class="docstring">
         
         </div> 
         </div>

                    
    <div class="darkcell">
    
    <A name=""></a>
    <b>def entity(<i>self</i>, <i>attr</i>)</b>
    <div class="docstring">
    
    </div>
    </div>

                    
    <div class="darkcell">
    
    <A name=""></a>
    <b>def flush(<i>self</i>)</b>
    <div class="docstring">
    
    </div>
    </div>

                    
    <div class="darkcell">
    
    <A name=""></a>
    <b>def join(<i>self</i>, <i>*args</i>, <i>**kwargs</i>)</b>
    <div class="docstring">
    
    </div>
    </div>

                    
    <div class="darkcell">
    
    <A name=""></a>
    <b>def map(<i>self</i>, <i>selectable</i>, <i>**kwargs</i>)</b>
    <div class="docstring">
    
    </div>
    </div>

                    
    <div class="darkcell">
    
    <A name=""></a>
    <b>def with_labels(<i>self</i>, <i>item</i>)</b>
    <div class="docstring">
    
    </div>
    </div>

                    
    <div class="darkcell">
    
    <A name=""></a>
    <b>def __getattr__(<i>self</i>, <i>attr</i>)</b>
    <div class="docstring">
    
    </div>
    </div>


    

            <a href="#top" class="totoc">back to section top</a>
    </div>



    

    </div>





    <div class="bottomnav">
        
    <div class="prevnext">
            Up: <a href="docstrings.html">API Documentation</a>

               |   
            Previous: <a href="sqlalchemy_ext_orderinglist.html">module sqlalchemy.ext.orderinglist</a>

               |   
            Next: <a href="sqlalchemy_databases_sqlite.html">module sqlalchemy.databases.sqlite</a>
    </div>

    </div>








</body>
</html>






